package com.jx.driving.protocol.terminal.codec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;

import com.jx.driving.util.BCDUtiils;

/**
 * Bcd属性读写器
 * 
 * @author shenliuyang
 *
 *         2016年7月29日下午6:31:01
 */
public class BcdFieldReaderWriter extends FieldReaderWriter {

	public BcdFieldReaderWriter(Field field, int size, int order) {
		super(field, size, order);
	}

	@Override
	public void read(InputStream in, Object to) throws IOException {
		byte[] data = new byte[size];
		in.read(data, 0, size);
		String bcd = BCDUtiils.bcd2Str(data);
		wrtietoField(to, bcd);
	}

	@Override
	public void write(OutputStream out, Object from) throws IOException {
		String bcd = (String) readFromField(from);
		byte[] data = new byte[size];
		if (bcd != null) {
			byte[] bcdData = BCDUtiils.str2Bcd(bcd);
			for (int i = 0; i < size; i++) {
				if (i >= bcdData.length) {
					break;
				}
				data[i] = bcdData[i];
			}
		}
		out.write(data);
	}

}